<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      const getData = () =>
        new Promise((resolve) => setTimeout(() => resolve('data'), 1000));

      function* testG() {
        // await被编译成了yield
        const data = yield getData();
        console.log('data: ', data);
        const data2 = yield getData();
        console.log('data2: ', data2);
        return 'success';
      }

      var test = asyncToGenerator(testG);

      function asyncToGenerator(fn) {
        return function (...args) {
          const gn = fn.apply(this, ...args);
          return new Promise((resolve, reject) => {
            function step(name, arg) {
              let result;
              try {
                result = gn[name](arg);
              } catch (error) {
                reject(error);
              }
              const { value, done } = result;
              if (done) {
                resolve(value);
              } else {
                Promise.resolve(value).then(
                  (data) => {
                    step('next', data);
                  },
                  (err) => {
                    step('throw', err);
                  }
                );
              }
            }
            step('next');
          });
        };
      }

      test().then((res) => console.log(res));
    </script>
  </body>
</html>
